package dLogistic.domain.service;

import dLogistic.domain.model.Klient.KlientAggr;
import dLogistic.domain.model.Klient.KlientRepository;
import dLogistic.domain.model.Magazyn.MagazynAggr;
import dLogistic.domain.model.Paczka.PaczkaAggr;
import dLogistic.domain.model.Paczka.TrasaPaczki;
import dLogistic.infrastructure.persistence.hibernate.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 * Created by Przemek on 2014-12-18.
 */
public class PaczkaService {
    private static SessionFactory factory;

    public void WyznaczTrasePaczki(PaczkaAggr paczkaAggr){
        KlientRepository klientRepository = new KlientRepository();
        //MagazynRepository magazynRepository = new MagazynRepository();
        MagazynAggr magNadAggr = null;
        MagazynAggr magAdrAggr = null;
        KlientAggr nadawcaAggr = klientRepository.znajdz(paczkaAggr.nadawca());
        KlientAggr adresatAggr = klientRepository.znajdz(paczkaAggr.adresat());

        if (nadawcaAggr != null){
            magNadAggr = klientRepository.najblizszyMagazyn(nadawcaAggr);
        }
        if (adresatAggr != null){
            magAdrAggr = klientRepository.najblizszyMagazyn(adresatAggr);
        }

        factory = HibernateUtil.getSessionFactory();
        Session session = factory.getCurrentSession();
        Transaction transaction = session.beginTransaction();
        if (magNadAggr != null){
            TrasaPaczki trasaPaczki1 = new TrasaPaczki(paczkaAggr.uuid(), nadawcaAggr.uuid(), magNadAggr.uuid(), 0 , 0);
            session.saveOrUpdate(trasaPaczki1);
        }
        if (magAdrAggr != null){
            TrasaPaczki trasaPaczki2 = new TrasaPaczki(paczkaAggr.uuid(), magAdrAggr.uuid(), adresatAggr.uuid(), 2 , 0);
            session.saveOrUpdate(trasaPaczki2);
        }

        if (magNadAggr != null && magAdrAggr != null){
            TrasaPaczki trasaPaczki2 = new TrasaPaczki(paczkaAggr.uuid(), magAdrAggr.uuid(), magNadAggr.uuid(), 1 , 1);
            session.saveOrUpdate(trasaPaczki2);

        }

        transaction.commit();
    }

    public PaczkaService(){

    };
}
